<?php
/**
 * 
 * 
 * $Rev: 7 $
 * $Author: thejahweh $
 * $Date: 2010-09-01 07:30:00 +0000 (Wed, 01 Sep 2010) $
 * $Id: permission.class.php 7 2010-09-01 07:30:00Z thejahweh $
 * $URL: http://allone.googlecode.com/svn/trunk/plugins/rbac/permission.class.php $
 * @author: Adrian Liechti <info@jahweh.ch>
 * @copyright: 2010 Adrian Liechti, GPL3 and CC3 BY-SA
 */

class permission {
	
	public $id;
	public $has;
	public $isLoaded = false;
	
	public function __construct ($id = true, $dbCheck = true) {
		if ($id === true) {
			$this->newPermission();
		} elseif ($id !== false) {
			$this->getById($id, $dbCheck);
		}
	}
	
	public function getById ($id, $dbCheck = true) {
		global $db;
		if ($dbCheck === true) {
			$permission_q = $db->query("
				SELECT *
				FROM permissions
				WHERE
					permission_id = ".$db->quote($id)."
				LIMIT 1;");
			if (false === ($permission_q !== false and $permission_q->fetch())) {
				return false;
			}
		}
		$this->id = $id;
		return $this->isLoaded = true;
	}

	public function has () {
		global $db, $user;
		if ($this->isLoaded !== true) {
			return false;
		} elseif ($this->has !== NULL) {
			return $this->has;
		} else {
			$right_q = $db->query("
				SELECT 
					p.role_id,
					uhr.user_id
				FROM 
					roles_has_permissions AS p,
					users_has_roles AS uhr
				WHERE 
					uhr.user_id = ".$db->quote($user->id)."
					AND p.role_id = uhr.role_id
					AND p.permission_id = ".$db->quote($this->id)."
				LIMIT 1;");
			if ($right_q !== false and $right_q->fetch()) {
				return $this->has = true;
			} else{
				return $this->has = false;
			}
		}
	}
	
	public function newPermission () {
		global $db;
		if ($db->exec("INSERT INTO permissions () VALUES ()")) {
			$this->id = $db->lastInsertId();
			return $this->isLoaded = true;
		} else {
			return false;
		}
	}
	
	public function addRole () {
		
	}
	
}
?>